<template>
    <div class="chat-box">
      <div class="chat-header">
        <div class="chat-title">百炼大模型聊天</div>
        <div class="chat-actions">
          <button class="chat-btn" @click="clearHistory">
            <i class="fas fa-trash"></i>
            清空记录
          </button>
          <button class="chat-btn">
            <i class="fas fa-download"></i>
            导出对话
          </button>
        </div>
      </div>
      <div class="messages-container" ref="messagesContainer">
        <div v-for="(message, index) in messages" :key="index"
             :class="['message', message.role]">
          <div class="avatar">
            <span v-if="message.role === 'user'">用</span>
            <span v-else>AI</span>
          </div>
          <div class="message-content">
            {{ message.content }}
            <div v-if="message.typing" class="typing-indicator">
              <div class="typing-dot"></div>
              <div class="typing-dot"></div>
              <div class="typing-dot"></div>
            </div>
            <div class="message-time">{{ message.time }}</div>
          </div>
        </div>
      </div>

      <div class="input-area">
                        <textarea v-model="inputText" placeholder="请输入您的问题..."
                                  @keydown.enter.prevent="sendMessage" :disabled="loading"></textarea>
        <button class="send-button" @click="sendMessage" :disabled="loading">
          <i class="fas fa-paper-plane"></i>
          {{ loading ? '发送中...' : '发送' }}
        </button>
      </div>
    </div>
</template>

<script>
export default {
  data() {
    return {
      messages,
      inputText,
      loading,
      messagesContainer,
      sendMessage,
      clearHistory,
      scrollToBottom
    };
  },
  mounted() {
    this.scrollToBottom()
  },
  methods: {
    // 清空聊天记录
    clearHistory() {
      messages.value = [{
        role: 'assistant',
        content: '对话历史已清空。请问有什么可以帮您？',
        typing: false,
        time: formatTime()
      }];
    },

    // 滚动到聊天区域底部
    scrollToBottom() {
      nextTick(() => {
        if (messagesContainer.value) {
          messagesContainer.value.scrollTop = messagesContainer.value.scrollHeight;
        }
      });
    },
// 发送消息到后端API
    sendMessage() {
      if (!inputText.value.trim() || loading.value) return;

      // 添加用户消息
      const userMessage = {
        role: 'user',
        content: inputText.value,
        typing: false,
        time: formatTime()
      };

      messages.value.push(userMessage);

      // 添加AI消息（初始为空）
      const aiMessage = {
        role: 'assistant',
        content: '',
        typing: true,
        time: formatTime()
      };

      messages.value.push(aiMessage);

      // 清空输入框
      const userInput = inputText.value;
      inputText.value = '';
      loading.value = true;

      // 滚动到底部
      scrollToBottom();

      try {  // 调用API
        const response = callAIApi(userInput);

        // 模拟流式输出效果
        aiMessage.typing = false;

        let index = 0;
        const interval = setInterval(() => {
          if (index < response.length) {
            aiMessage.content += response.charAt(index);
            index++;
            scrollToBottom();
          } else {
            clearInterval(interval);
            loading.value = false;
            aiMessage.time = formatTime();
          }
        }, 30);
      } catch (error) {
        console.error('API调用失败:', error);
        aiMessage.typing = false;
        aiMessage.content = '抱歉，服务暂时不可用，请稍后再试。';
        loading.value = false;
        aiMessage.time = formatTime();
      }
    }
  }
}
</script>

<style scoped>
.chat-box {
  flex: 1;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.chat-header {
  padding: 16px 20px;
  background: linear-gradient(90deg, #3498db 0%, #2c3e50 100%);
  color: white;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.chat-title {
  font-size: 1.1rem;
  font-weight: 600;
}

.chat-actions {
  display: flex;
  gap: 10px;
}

.chat-btn {
  padding: 6px 12px;
  background: rgba(255, 255, 255, 0.2);
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 5px;
  font-size: 0.85rem;
}

.messages-container {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.message {
  display: flex;
  gap: 15px;
  max-width: 80%;
}

.message.user {
  align-self: flex-end;
  flex-direction: row-reverse;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: bold;
  flex-shrink: 0;
  background-color: #3498db;
  color: white;
}

.message.user .avatar {
  background-color: #2c3e50;
}

.message-content {
  padding: 12px 16px;
  border-radius: 8px;
  line-height: 1.5;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
}

.user .message-content {
  background: linear-gradient(135deg, #3498db 0%, #2c3e50 100%);
  color: white;
}

.assistant .message-content {
  background-color: #f1f5f9;
  color: #2c3e50;
}

.message-time {
  font-size: 0.75rem;
  opacity: 0.7;
  margin-top: 6px;
}

.input-area {
  padding: 20px;
  background-color: white;
  border-top: 1px solid #eaeaea;
  display: flex;
  gap: 15px;
}

textarea {
  flex: 1;
  padding: 12px 16px;
  border: 1px solid #e0e0e0;
  border-radius: 6px;
  resize: none;
  height: 50px;
  font-size: 1rem;
  outline: none;
  transition: border-color 0.3s;
}

textarea:focus {
  border-color: #3498db;
}

button.send-button {
  padding: 0 20px;
  background: linear-gradient(135deg, #3498db 0%, #2c3e50 100%);
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 600;
  transition: opacity 0.2s;
  display: flex;
  align-items: center;
  gap: 8px;
}

button.send-button:hover {
  opacity: 0.9;
}

button.send-button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.typing-indicator {
  display: inline-flex;
  gap: 4px;
  align-items: center;
  margin-top: 8px;
}

.typing-dot {
  width: 6px;
  height: 6px;
  background-color: #7f8c8d;
  border-radius: 50%;
  animation: typingAnimation 1.4s infinite ease-in-out;
}

.typing-dot:nth-child(1) {
  animation-delay: 0s;
}

.typing-dot:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-dot:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typingAnimation {
  0%, 60%, 100% {
    transform: translateY(0);
  }
  30% {
    transform: translateY(-5px);
  }
}

.api-status {
  padding: 10px 20px;
  background-color: #f1f5f9;
  border-top: 1px solid #eaeaea;
  display: flex;
  align-items: center;
  gap: 10px;
  font-size: 0.9rem;
  color: #64748b;
}

.status-indicator {
  width: 10px;
  height: 10px;
  border-radius: 50%;
  background-color: #2ecc71;
}

</style>
